package com.macllvm.whale.model;

import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Observable;

import com.macllvm.whale.adapter.*;
import com.macllvm.whale.entity.Buddy;
import com.macllvm.whale.entity.Message;

import android.util.Log;

public class BuddyManager extends Observable  {
    private static final String TAG = "BuddyManager";

    private List<Buddy> list = new LinkedList<Buddy>();
    private ConcurrentMap<String, Integer> ipCache = new ConcurrentHashMap<String, Integer>();
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void add(Buddy b){
        Lock l = lock.writeLock();
        l.lock();
        try {
            if (!contain(b.getIP())) {
                ipCache.put(b.getIP(), list.size());
                list.add(b);
                this.setChanged();
                this.notifyObservers();
            }
        } finally {
            l.unlock();
        }
    }

    public Buddy get(String ip) {
        Buddy b = null;
        if(ipCache.size() == 0) return b;
        int index = -1;
        try {
            index = ipCache.get(ip);
        }catch(Exception e) {
            e.toString();
        }
        if(index >= 0) {
            Lock l = lock.readLock();
            l.lock();
            try {
                b = list.get(index);
            } finally {
                l.unlock();
            }
        }
        return b;
    }

    public Buddy get(int pos) {
        Buddy b = null;
        if(pos >= 0) {
            Lock l = lock.readLock();
            l.lock();
            try {
                b = list.get(pos);
            } finally {
                l.unlock();
            }
        }
        return b;
    }


    public void refresh() {
        this.setChanged();
        this.notifyObservers();
    }

    public boolean contain(String ip){
        return ipCache.containsKey(ip);
    }

    public List<Buddy> getDataSource() {
        return list;
    }

}